package xyz.suancaiyu.userservice.aop;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.suancaiyu.annotation.SysLogger;
import xyz.suancaiyu.userservice.entity.SysLog;
import xyz.suancaiyu.userservice.service.LoggerService;
import xyz.suancaiyu.userservice.util.HttpUtils;
import xyz.suancaiyu.userservice.util.UserUtils;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author puruidong
 * @version 2019/1/24 22:23
 */
@Aspect
@Component
public class SysLoggerAspect {

    @Autowired
    private LoggerService loggerService;

    @Pointcut("@annotation(xyz.suancaiyu.annotation.SysLogger)")
    public void loggerPointCut() {

    }

    @Before("loggerPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        SysLogger sysLogger = method.getAnnotation(SysLogger.class);
        if (sysLogger != null) {
            // 注解的描述
            sysLog.setOperation(sysLogger.value());
        }
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        // 请求参数
        Object[] args = joinPoint.getArgs();
        // TODO
        String params = Stream.of(args).map(o -> JSON.toJSONString(o)).collect(Collectors.joining());
        System.out.println("**************************************************");
        System.out.println(params);
        System.out.println("**************************************************");
        if (!StringUtils.isEmpty(params)) {
            sysLog.setParams(params);
        }
        sysLog.setIp(HttpUtils.getIpAddress());
        String username = UserUtils.getCurrentPrinciple();
        if (!StringUtils.isEmpty(username)) {
            sysLog.setUsername(username);
        }
        sysLog.setCreateDate(new Date());
        //保存系统日志
        loggerService.log(sysLog);
    }


}
